<?php

namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\mosquito\InfoModel;
use bc\util\backend\Page;

class MosquitoController extends BackendController
{
	
	public function actionIndex()
	{
		$view = [];
		$model = new InfoModel();
		
		$params = 'is_play = 1';
		
		$page = $this->get('page', 1);
		
		$type = $this->get('type', 1);
		
		$baby_name = $this->get('baby_name');
		
		if($baby_name)
		{
			$params .= ' AND mosquito_nick_name LIKE "%' . $baby_name . '%"';
		}
		
		if($type == 1)//时间
		{
			$sort = 'max_time DESC, create_time ASC';
		}
		else//总共打死的蚊子数
		{
			$sort = 'total_num DESC, create_time ASC';
		}
		$model->sort = $sort;
		$list = $model->getList($params, $page, self::PAGE_SIZE);
		
		$total = $model->getTotal($params);
		
		$pagination = new Page($total, self::PAGE_SIZE);
		
		$view['list'] = $list;
		$view['pagination'] = $pagination;
		$view['type'] = $type;
		$view['baby_name'] = $baby_name;
		
		return $this->render('index', $view);
		
	}
	
    public function actionEdit()
	{
		$id = $this->get('id');
		if(!$id)
			$this->redirect('/');
		
		$model = new InfoModel();
		$row = $model->getRowById($id);
		
		if(!$row)
			$this->redirect('/');
		
		$view['row'] = $row;
		return $this->render('edit', $view);
	}
	
	
	/**
	 * 保存
	 */
	public function actionSave()
	{
		
		if($this->getRequest()->isPost)
		{
			$id = $this->post('id');
			if(!$id)
				$this->redirect('/');
			
			$model = new InfoModel();
			$row = $model->getRowById($id);
			
			if(!$row)
				$this->redirect('/');
	
			$max_time = floatval($this->post('max_time'));
			$total_number = $this->post('total_num');
			
			$blood = $this->post('blood', null);
			if($blood)
			{
				$data['blood'] = $blood;
			}
			
			
			$data['max_time'] = $max_time;
			$data['total_num'] = $total_number;
			$model->modify($data, $id);
			
			$output['msg'] = '保存成功！';
		}
		else 
		{
			$output['msg'] = '请求错误！';
		}
		$output['url'] = '/mosquito';
		$this->forward($output);
	}
}

